package com.mlxg.master.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlxg.master.domain.HzExhibitsReceive;
import com.mlxg.master.mapper.HzExhibitsReceiveMapper;
import com.mlxg.master.service.HzExhibitsReceiveService;
import com.mlxg.selver.domain.ExhibitClassificationNode;
import com.mlxg.selver.domain.HzExhibitsSlave;
import com.mlxg.selver.domain.HzProductServicesIdMapping;
import com.mlxg.selver.domain.IdMapping;
import com.mlxg.selver.service.IExhibitClassificationNodeService;
import com.mlxg.selver.service.IHzExhibitsSlaveService;
import com.mlxg.selver.service.IHzProductServicesIdMappingService;
import com.mlxg.selver.service.IIdMappingService;
import com.mlxg.untils.oss.GeneralOSSUpLoadUtils;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.sql.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 在线展品申请 服务实现类
 * </p>
 *
 * @author zcy
 * @date 2025/5/23 9:50
 */
@Slf4j
@Service
@DS("master")
public class HzExhibitsReceiveServiceImpl extends ServiceImpl<HzExhibitsReceiveMapper, HzExhibitsReceive> implements HzExhibitsReceiveService {

    @Autowired
    private HzExhibitsReceiveMapper hzExhibitsReceiveMapper;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private IIdMappingService iIdMappingService;

    /**
     * 自定义展品id映射
     */
    @Autowired
    private IHzProductServicesIdMappingService hzProductServicesIdMappingService;

    /**
     * new展品Service
     */
    @Autowired
    private IHzExhibitsSlaveService hzExhibitsSlaveService;
    /**
     * 产品类型
     */
    @Autowired
    private IExhibitClassificationNodeService exhibitClassificationNodeService;

    /**
     * 通用文件上传
     */
    @Autowired
    private GeneralOSSUpLoadUtils generalOSSUpLoadUtils;

    /**
     * 展品数据同步
     */
    @Override
    public void transferHzExhibits() {

        int pageSize = 1000;
        int pageNum = 1;
        int totalProcessed = 0;
        int totalSuccess = 0;
        int totalFailed = 0;
        int totalPageFailed = 0;
        int noFindMapping=0;
        log.info("开始展商产品系列数据迁移，每页处理 {} 条记录", pageSize);
        // 定义展品类型ID映射
        Map<String, ExhibitClassificationNode> exhibitClassificationNodeMap = new ConcurrentHashMap<>();
        // 展品展商ID映射
        Map<String, IdMapping> exhibitorIdMappingConcurrentHashMap = new ConcurrentHashMap<>();
        // 自定义展品类型ID映射
        Map<String, HzProductServicesIdMapping> hzProductServicesIdMappingConcurrentHashMap = new ConcurrentHashMap<>();

        QueryWrapper<ExhibitClassificationNode> exhibitClassificationNodeQueryWrapper = new QueryWrapper<>();
//        exhibitClassificationNodeQueryWrapper.select("id", "name", "name_en");
        QueryWrapper<HzExhibitsReceive> queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id","hzExhibitor_id","exhibits_name","Column_25","Column_23","Column_19"
                ,"apply_time","Column_11","Column_15","exhibits_img","exhibits_attach",
                "exhibits_intro","exhibits_intro_e","tech_param","Column_24","Column_20","Column_21");
        queryWrapper.in("del_flag", "0", "2");
        queryWrapper.isNotNull("hzExhibitor_id");

        List<HzExhibitsReceive> hzExhibitsReceiveList = null;
        do {
            try {
                // 分页查询
                Page<HzExhibitsReceive> page = new Page<>(pageNum, pageSize);
                hzExhibitsReceiveList = hzExhibitsReceiveMapper.selectPage(page, queryWrapper).getRecords();

                if (CollectionUtil.isEmpty(hzExhibitsReceiveList)) {
                    log.info("分页查询完成，没有更多数据，共处理 {} 页", pageNum - 1);
                    break;
                }

                // 记录总处理条数
                totalProcessed += hzExhibitsReceiveList.size();
                log.info("开始处理第 {} 页数据，当前页记录数: {}", pageNum, hzExhibitsReceiveList.size());

                int pageSuccess = 0;
                int pageFailed = 0;

                // 处理当前页的所有记录
                for (HzExhibitsReceive oldHzExhibitsReceive : hzExhibitsReceiveList) {
                    try {
                        log.debug("开始处理展品记录 - ID: {}", oldHzExhibitsReceive.getId());

                        HzExhibitsSlave newHzExhibitsSlave = modelMapper.map(oldHzExhibitsReceive, HzExhibitsSlave.class);

                        // 设置展商ID
                        String exhibitorId = oldHzExhibitsReceive.getHzexhibitorId();
                        if (StringUtils.isEmpty(exhibitorId)) {
                            throw new RuntimeException("此展品没有绑定展商，数据ID: " + oldHzExhibitsReceive.getId());
                        }

                        IdMapping idMapping = exhibitorIdMappingConcurrentHashMap.computeIfAbsent(exhibitorId,
                                key -> iIdMappingService.getById(key));

                        if (idMapping == null) {

                            noFindMapping++;
                            throw new RuntimeException("未找到展商ID映射关系，exhibitorId: " + exhibitorId);
                        }

                        // 设置展商ID
                        newHzExhibitsSlave.setUserId(idMapping.getUserId());

                        // 处理产品类型
                        String column19 = oldHzExhibitsReceive.getColumn19();
                        if (StringUtils.isEmpty(column19)) {
                            log.warn("数据产品类别为其他产品类别,数据ID={}==原展商id为={}",
                                    oldHzExhibitsReceive.getId(), oldHzExhibitsReceive.getHzexhibitorId());
                        } else {
                            exhibitClassificationNodeQueryWrapper.clear();
                            exhibitClassificationNodeQueryWrapper.select("id", "name", "name_en");

                            // 根据column19首字符决定查询条件
                            if (column19 != null && !column19.isEmpty() && Character.isUpperCase(column19.charAt(0))) {
                                exhibitClassificationNodeQueryWrapper.eq("name_en", column19);
                            } else {
                                exhibitClassificationNodeQueryWrapper.eq("name", column19);
                            }

                            ExhibitClassificationNode exhibitClassificationNode = exhibitClassificationNodeMap.computeIfAbsent(column19,
                                    key -> exhibitClassificationNodeService.getOne(exhibitClassificationNodeQueryWrapper, false));

                            if (exhibitClassificationNode != null) {
                                newHzExhibitsSlave.setProductTypeId(exhibitClassificationNode.getId());
                            } else {
                                log.warn("未找到产品类型映射关系，column19: {}", column19);
                            }
                        }

                        // 处理自定义产品类型
                        String column15 = oldHzExhibitsReceive.getColumn15();
                        if (StringUtils.isEmpty(column15)) {
                            log.warn("自定义产品类别为空,数据ID={}==原展商id为={}",
                                    oldHzExhibitsReceive.getId(), oldHzExhibitsReceive.getHzexhibitorId());
                        } else {
                            HzProductServicesIdMapping hzProductServicesIdMapping = hzProductServicesIdMappingConcurrentHashMap.computeIfAbsent(column15,
                                    key -> hzProductServicesIdMappingService.getById(key));
                            if (hzProductServicesIdMapping != null) {
                                newHzExhibitsSlave.setProductCustomizeType(hzProductServicesIdMapping.getNewHzProductServicesId());
                            } else {
                                log.info("未找到自定义展品ID的映射关系，column15: {}", column15);
                            }
                        }

                        // 处理展品图片
                        newHzExhibitsSlave.setProductPictureUrl(
                                processUrlField(oldHzExhibitsReceive.getExhibitsImg(), "productImages"));

                        // 处理展品资料
                        newHzExhibitsSlave.setProductInformationUrl(
                                processUrlField(oldHzExhibitsReceive.getExhibitsAttach(), "productMaterials"));

                        // 处理展品宣传视频封面
                        newHzExhibitsSlave.setProductVideoImageUrl(
                                processUrlField(oldHzExhibitsReceive.getColumn20(), "productVideoImages"));

                        // 处理产品视频
                        newHzExhibitsSlave.setProductVideoUrl(
                                processUrlField(oldHzExhibitsReceive.getColumn21(), "productVideos"));
                        newHzExhibitsSlave.setApplyTime(Date.valueOf(oldHzExhibitsReceive.getApplyTime().toLocalDate()));
                        // 保存新记录
                        hzExhibitsSlaveService.save(newHzExhibitsSlave);
                        pageSuccess++;
                        totalSuccess++;
                        log.debug("展品记录处理成功 - ID: {}", oldHzExhibitsReceive.getId());

                    } catch (Exception e) {
                        pageFailed++;
                        totalFailed++;
                        log.error("处理单条记录失败 - 数据ID: {}, 错误信息: {}",
                                oldHzExhibitsReceive.getId(), e.getMessage(), e);
                    }
                }

                // 记录分页处理结果
                log.info("第 {} 页处理完成 - 成功: {}, 失败: {}", pageNum, pageSuccess, pageFailed);
                pageNum++;

            } catch (Exception e) {
                totalPageFailed++;
                log.error("处理第 {} 页数据失败，错误信息: {}", pageNum, e.getMessage(), e);
                pageNum++;
            }
        } while (hzExhibitsReceiveList != null && hzExhibitsReceiveList.size() == pageSize);

        log.info("数据迁移完成 - 总共处理页数: {}, 总记录数: {}, 成功: {}, 失败: {}, 分页处理失败: {},未找到展商id的映射关系一共={}",
                pageNum - 1, totalProcessed, totalSuccess, totalFailed, totalPageFailed,noFindMapping);

        // 记录迁移总结
        if (totalFailed > 0 || totalPageFailed > 0) {
            log.warn("数据迁移存在部分失败，请检查错误日志进行修复");
        } else {
            log.info("数据迁移全部成功完成");
        }
    }
    /**
     * 处理URL字段，将相对路径转换为OSS地址
     */
    private String processUrlField(String fieldValue, String ossDir) throws IOException {
        if (StringUtils.isBlank(fieldValue)) {
            return null;
        }

        if (fieldValue.startsWith("/")) {
            StringBuilder urlBuilder = new StringBuilder();
            String[] parts = fieldValue.split(",");

            for (int i = 0; i < parts.length; i++) {
                String part = parts[i];
                if (part.startsWith("http://") || part.startsWith("https://")){
                    urlBuilder.append(part);
                    if (i < parts.length - 1) {
                        urlBuilder.append(",");
                    }
                }else {
                    String url = generalOSSUpLoadUtils.uploadUrlToOss(part, ossDir);
                    urlBuilder.append(url);
                    if (i < parts.length - 1) {
                        urlBuilder.append(",");
                    }
                }
            }

            return urlBuilder.toString();
        } else if (fieldValue.startsWith("http://") || fieldValue.startsWith("https://")) {
            return fieldValue;
        }

        return null;
    }

    public static void main(String[] args) {
        String str ="/hz/hzupload/2/e8a6f37366bd4243ac42bb993223e0b0/20210830/1630320201498微信图片_20210830181910.jpg,/hz/hzupload/2/e8a6f37366bd4243ac42bb993223e0b0/20210830/1630320260978微信图片_20210830181854.jpg";
        if (str.startsWith("/")){
            String[] split = str.split(",");
            for (String s : split) {

                System.out.println("s = " + s);
            }
        }
    }
}
